﻿using Newtonsoft.Json;
using WholesaleOnline.Contract;
using WholesaleOnline.Controller.Extension;
using WholesaleOnline.Controller.Request;
using WholesaleOnline.Controller.Routing;
using WholesaleOnline.Controller.Storage;
using WholesaleOnline.DataContract.Messaging;

namespace WholesaleOnline.Controller.Handlers
{
    public class GetBasketsHandler : RequestHandler
    {
        private IBasketService m_basketService = null;

        public GetBasketsHandler(IHttpStorage storage, IBasketService basketService)
            : base(Routes.GET_BASKETS, storage)
        {
            m_basketService = basketService;
        }

        public override void Handle(WebRequest webRequest)
        {
            if (Route.Matches(webRequest))
            {
                GetBasketsRequest request = new GetBasketsRequest();
                request.BuyerId = webRequest.LoginId;

                GetBasketsResponse response = m_basketService.GetBasketsBy(request);
                if (response.Success)
                {
                    var dynamicObj = response.Baskets.ConvertToBasketJsonModel();
                    Storage.Add(HttpStorageKeys.Json, JsonConvert.SerializeObject(dynamicObj));
                }
                else
                {
                    Storage.Add(HttpStorageKeys.Exception, response.Message);
                    Storage.Add(HttpStorageKeys.Json, "[]");
                }
            }
            else
            {
                base.NextHandler.Handle(webRequest);
            }
        }
    }
}
